/*
 * Copyright 2011 Katsunori Koyanagi
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

package sweezy.easing
{
	import flash.display.Graphics;
	import mx.core.UIComponent;
	import sweezy.anim.core.IEasing;
	import sweezy.anim.easing.Linear;

	public class Graph extends UIComponent
	{

		private var _easing:IEasing;

		private var _time:uint;

		public function Graph()
		{
			buttonMode = true;
			useHandCursor = true;
		}

		public function get easing():IEasing
		{
			return _easing;
		}

		public function set easing(value:IEasing):void
		{
			_easing = value;
			invalidateDisplayList();
		}

		public function get time():uint
		{
			return _time;
		}

		public function set time(value:uint):void
		{
			_time = value;
			invalidateDisplayList();
		}

		override protected function updateDisplayList(unscaledWidth:Number, unscaledHeight:Number):void
		{
			super.updateDisplayList(unscaledWidth, unscaledHeight);

			var g:Graphics = graphics;
			g.clear();
			g.beginFill(0xaaaaaa);
			g.drawRect(0, 0, unscaledWidth, unscaledHeight);
			g.drawRect(1, 1, unscaledWidth - 2, unscaledHeight - 2);
			g.endFill();

			if (_easing === null)
			{
				_easing = Linear.easeNone;
			}

			g.beginFill(0xffffff);
			var t:Number = _easing.ease(_time / 1000);
			if (t * 0 !== 0)
			{
				t = 0;
			}
			g.drawRect(1, 1, (unscaledWidth - 2) * t, unscaledHeight - 2);
			g.endFill();

			g.lineStyle(2, 0xff9955, 1);
			g.moveTo(0, unscaledHeight - _easing.ease(0));
			for (var i:int = 5; i < _time; i += 5)
			{
				g.lineTo(i / 1000 * unscaledWidth, unscaledHeight * (1 - (_easing.ease(i / 1000) || 0)));
			}
			g.lineTo(_time / 1000 * unscaledWidth, unscaledHeight * (1 - t));
			g.lineStyle();
			if (_time < 1000)
			{
				g.beginFill(0xff0000);
				g.drawCircle(_time / 1000 * unscaledWidth, unscaledHeight * (1 - t), 3);
				g.endFill();
			}
		}
	}
}
